import React from "react";
import {AppHeader} from "../common/AppHeader";
import {Group} from "../data/Group";
import {User} from "../data/User";
import {AppConfig} from "../config/AppConfig";
import {Cookies} from "../common/Cookies";
import {Http} from "../config/Http";
import {Urls} from "../config/Urls";
import {AppLoading} from "./AppLoading";
import {Login} from "./Login";
import {AppHome} from "./AppHome";
import {Route} from "react-router";

export class AppContent extends React.Component<any, { currentGroup: Group, user: User, login: boolean, init: boolean }> {
    constructor(props: any) {
        super(props);
        this.state = {currentGroup: {name: 'NA'}, user: {}, login: false, init: true};
        AppConfig.startInit().then(() => {
            AppContent.checkLogin().then((user) => {
                    if (user && user.username) {
                        if (user.groups && user.groups.length > 0) {
                            let group = user.groups[0];
                            this.setState({
                                init: false,
                                login: true,
                                user: user,
                                currentGroup: group
                            });
                            this.goGroupHome(group);
                        } else {
                            this.setState({
                                init: false,
                                login: true,
                            });
                        }
                    } else {
                        this.setState({
                            init: false,
                            login: false
                        })
                    }

                }
            ).catch((): void => {
                this.setState({
                    init: false,
                    login: false
                })
            })
        });
    }

    private static checkLogin(): Promise<User> {
        let token = Cookies.getCookie(Cookies.TOKEN_KEY);
        if (token && token.length > 0) {
            return Http.get(Urls.GET_TOKEN_USER);
        }
        return Promise.resolve<User>({});
    }

    private onGroupCreated(group: Group): void {
        if (this.state.user.groups) {
            this.state.user.groups.push(group);
            this.setState({});
        } else {
            this.setState({
                user: {groups: [group]}
            })
        }
    }


    private login(tokenInfo: any) {
        if (tokenInfo.hasOwnProperty(Cookies.TOKEN_KEY)) {
            Cookies.setCookie(Cookies.TOKEN_KEY, tokenInfo[Cookies.TOKEN_KEY]);
        }
        Http.get<User>(Urls.GET_TOKEN_USER).then((user: User) => {
            if (user.groups && user.groups[0]) {
                this.setState({
                    user: user,
                    currentGroup: user.groups ? user.groups[0] : this.state.currentGroup
                });
                this.goGroupHome(user.groups[0]);
            } else {
                this.setState({
                    user: user
                });
            }
        });
        this.setState({
            login: true
        })
    };

    private onGroupSelect(group: Group) {
        this.setState({currentGroup: group});
        this.goGroupHome(group);
    }

    private onHomeSelect(group: Group) {
        this.goGroupHome(group);
    }

    render(): React.ReactElement<any, string | React.JSXElementConstructor<any>> | string | number | {} | React.ReactNodeArray | React.ReactPortal | boolean | null | undefined {
        if (this.state.init) {
            return <AppLoading/>
        } else {
            if (this.state.login) {
                return <div>
                    <AppHeader user={this.state.user} onGroupSelect={this.onGroupSelect.bind(this)}
                               onGroupCreate={this.onGroupCreated.bind(this)}
                               currentGroup={this.state.currentGroup}
                               onHomeSelect={this.onHomeSelect.bind(this)}
                    />
                    <Route path={'/:groupId/home'} component={AppHome}/>
                </div>;
            }
            return <Login login={this.login.bind(this)}/>;
        }

    }

    private goGroupHome(group: Group) {
        this.props.history.push('/' + group.id + '/home');
    }
}